<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\library\Map\Factory;

use app\common\library\Curl;
use app\common\library\Map\Interfaces\MapService;
use think\Exception;

class Tencent implements MapService
{
    private $curl;
    protected $key;
    protected $secret;
    protected $domain = 'https://apis.map.qq.com';
    protected $IpUrl = '/ws/location/v1/ip?';
    protected $LocationUrl = '/ws/geocoder/v1?';
    public function __construct($config)
    {
        $this->key = $config['tencentkey'];
        $this->secret = $config['secret'];
        $this->curl = new Curl();
    }
    public function sign( $url,array $data)
    {
        try {
            ksort($data);
            return md5($url.urldecode(http_build_query($data)).$this->secret);

        }catch (Exception $exception){
            return '';
        }
    }
    public function getInfoByIp($ip)
    {
        $this->curl->setUrl($this->domain.$this->IpUrl);
        $sign = $this->sign($this->IpUrl,['ip'=>$ip,'key'=>$this->key]);
        $this->curl->get(urldecode(http_build_query(['ip'=>$ip,'sig'=>$sign,'key'=>$this->key])));
        return  $this->curl->exec();
    }

    public function getInfoByAddress($address)
    {
        $this->curl->setUrl($this->domain.$this->IpUrl);
        $this->curl->get(['address'=>$address]);
        return $this->curl->exec();
    }

    public function getInfoByLocation($location){
        $this->curl->setUrl($this->domain.$this->LocationUrl);
        $sign = $this->sign($this->LocationUrl,['location'=>$location,'key'=>$this->key]);
        $this->curl->sslVerify(false);
        $this->curl->get(urldecode(http_build_query(['location'=>$location,'sig'=>$sign,'key'=>$this->key])));
        return $this->curl->exec();
    }

}